#include <CascadeFormat.h>

const CascadeFormat& CASCADE_FORMAT = CascadeFormat::getInstance();

const CascadeFormat& CascadeFormat::getInstance()
{
    static const CascadeFormat  cascadeFormat();
    return cascadeFormat;
}

void CascadeFormat::toString(std::ostream & os,const int value, const Unit &unit)
{
    Unit* p_unit = NULL;    
    int quotient = 0;
    int remain = (int)(unit.toBaseVlaue(value_m));
    if(unit.getMaxUnit(&p_unit) && remain != 0)
    {
        do
        {
            getRemainAndQuotient(p_unit, remain, quotient);
            printDelimiter(os,p_unit);
            p_unit->toString(os,quotient); 
        }while(remain != 0 && unit.getNextMaxUnit(&p_unit));
    }
}


void CascadeFormat::getRemainAndQuotient(const Unit *p_unit, int &remain, int &quotient)
{   
    int ratio = (int)(p_unit->getRatioToBase());
    quotient = remain / ratio;
    remain = remain % ratio;  
}

void CascadeFormat::printDelimiter(std::ostream & os, const Unit* const p_unit)
{
    if(p_unit != NULL)
    { 
        Unit* p_maxUnit = NULL;
        if(p_unit->getMaxUnit(&p_maxUnit) && p_maxUnit != p_unit)
        {
            os<<" ";
        }
    }
}







